<?php

declare(strict_types=1);

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Search\UserInterface\Controller\Website;

use CmsIg\Seal\EngineInterface;
use CmsIg\Seal\Search\Condition\Condition;
use Sulu\Bundle\WebsiteBundle\Resolver\TemplateAttributeResolverInterface;
use Sulu\Component\Webspace\Analyzer\RequestAnalyzerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Twig\Environment;

class SearchController
{
    public function __construct(
        private readonly EngineInterface $engine,
        private readonly RequestAnalyzerInterface $requestAnalyzer,
        private readonly Environment $twig,
        private readonly TemplateAttributeResolverInterface $templateAttributeResolver,
    ) {
    }

    public function queryAction(Request $request): Response
    {
        $query = $request->query->get('q', '');

        $locale = $this->requestAnalyzer->getCurrentLocalization()->getLocale();
        $webspace = $this->requestAnalyzer->getWebspace();

        $hits = [];

        if ($query) {
            $search = $this->engine->createSearchBuilder('website')
                ->addFilter(Condition::search($query));

            if ($locale) {
                $search->addFilter(Condition::equal('locale', $locale));
            }

            $search->addFilter(Condition::equal('webspaces', $webspace->getKey()));

            $search->highlight(['title', 'content'], '<mark>', '</mark>');
            $result = $search->getResult();

            foreach ($result as $document) {
                $hits[] = $document;
            }
        }

        $template = $webspace->getTemplate('search', (string) $request->getRequestFormat());

        if (!$template || !$this->twig->getLoader()->exists($template)) {
            throw new NotFoundHttpException();
        }

        $parameters = ['query' => $query, 'hits' => $hits];

        $parameters = $this->templateAttributeResolver->resolve($parameters);

        $response = new Response($this->twig->render($template, $parameters));

        return $response;
    }
}
